<template>
  <div class="main">
    <PureTableBar title="应收账款列表" class="list_hei">
      <template #buttons>
        <el-button type="primary" @click="addVisible = true">添加应收账款凭证</el-button>
      </template>
      <template v-slot="{ size, checkList }">
        <pure-table border align-whole="center" showOverflowTooltip table-layout="auto" adaptive size="small"
          :data="dataList" max-height="600" :columns="columns" :pagination="pagination" @size-change="getList"
          @current-change="getList" :checkList="checkList" :header-cell-style="{
            background: 'var(--el-table-row-hover-bg-color)',
            color: 'var(--el-text-color-primary)'
          }">
          <template #operation="{ row }">
            <el-button type='primary' size="small" text @click="showDetail(row)"> 详情 </el-button>
          </template>
        </pure-table>
      </template>
    </PureTableBar>
  </div>
  <ReDialog :width="1000" :height="400" :models="addVisible" @Closes="cancel1()">
    <template #header>
      <h2 style=" text-align: center;">付款承诺函</h2>
    </template>
    <template #main>
      <div class="container">
        <div class="content">
          <div style="text-align: left;">
            <p style="margin-bottom: 20px;">
              <el-select placeholder="请选择" class="!w-[180px]" v-model="formData.supId" @change="handleChangeSup">
                <el-option v-for="item in suppierList" :key="item.seiId" :label="item.supplyName" :value="item.seiId" />
              </el-select>
              <span style="margin-left: 10px;">:</span>
            </p>
            <p style="margin-bottom: 20px;">&nbsp;&nbsp;&nbsp;&nbsp;根据我司与贵司签订的 <el-select placeholder="请选择"
                class="!w-[180px]" v-model="formData.contractId">
                <el-option v-for="item in contractList" :key="item.purchaseSaleContractId" :label="item.purchaseName"
                  :value="item.purchaseSaleContractId" @click="handleChangeContract(item)" />
              </el-select>的约定，我司承诺：在
              <span style="text-decoration:underline ;">{{ formData.year }}</span>年<span
                style="text-decoration:underline ;">{{
                  formData.month }}</span>月<span style="text-decoration:underline ;">{{ formData.day }}</span>日前，向贵司归还合同款¥
              {{ formData.money }}元（大写：<el-input v-model.trim="formData.BigMoney" style="width:150px"
                @blur="handleInput"></el-input>）。
            </p>
            <p style=" margin-bottom: 20px;"> &nbsp;&nbsp;&nbsp;&nbsp;我司承诺及时做好资金安排，按时足额支付上述款项。
            </p>
            <div class="DispatchForm_date">
              <ul>
                <span class="mySignet" id="view_FQX1" v-if="isSeal"></span>
                <li>承诺人（盖章）<el-button text :icon="useRenderIcon(EStamp)" title="盖章" @click="Signet"
                    v-if="!isSeal"></el-button>
                </li>
              </ul>
              <ul>
                <span class="mySignet" id="view_FQX2" v-if="isSeal1"></span>
                <li>法人代表（盖章）<el-button text :icon="useRenderIcon(EStamp)" title="盖章" @click="Signet1"
                    v-if="!isSeal1"></el-button>
                </li>
              </ul>
            </div>
          </div>
        </div>
      </div>
    </template>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="save()" type="primary">确定</el-button>
        <el-button @click="cancel1()"> 取消 </el-button>
      </span>
    </template>
  </ReDialog>
</template>
<script setup lang='ts'>
import { ElMessage, FormInstance } from "element-plus";
import { type PaginationProps } from "@pureadmin/table";
import { PureTableBar } from "@/components/RePureTableBar";
import {
  GetHaveInStockPurchaseSupplierEnterprise,
  GetHaveSignedPurchaseOrderContract,
  GetDictionaryByDictCode,
  AccountsReceivableCertificateCreate,
  AccountsReceivableCertificateGetAllByPagedAndSort,
} from "@/api/stu/SupplyChainFinance"
import { useRoute } from "vue-router";
import { useRenderIcon } from "@/components/ReIcon/src/hooks";
import EStamp from "@iconify-icons/ep/stamp";
import { FXQ } from "@/utils/public/FXQ"
import { ref, reactive, nextTick, watch, onMounted } from "vue";
import qs from "qs";
const route = useRoute();
const suppierList = ref([])
const contractList = ref([])
const paymentList = ref([])
const formData = ref({
  supId: '',
  contractId: '',
  year: '',
  month: '',
  day: '',
  money: '',
  BigMoney: '',
  collectionDate: '',
})
const pagination = reactive<PaginationProps>({
  total: 0,
  pageSize: 10,
  currentPage: 1,
  pageSizes: [5, 10, 15],
  background: true
});
const addVisible = ref(false)
const dataList = ref();
const columns = [
  {
    label: "序号",
    type: "index",
    fixed: "left",
    minWidth: 50
  },
  {
    label: "采购项目名称",
    prop: "purchaseName",
  },
  {
    label: "总金额（元）",
    prop: "contractAmount",
  },
]
const inputRegx = /^[\u4e00-\u9fa5]+$/
const isSeal = ref(false)
const isSeal1 = ref(false)

function Signet() {
  isSeal.value = true
  // // 生成章
  nextTick(() => {
    const MYFXQ = FXQ.companySeal('****电商公司', 0, 0, '', '');
    let view_FQX = document.querySelector("#view_FQX1");
    let MYFQX = `<img src='${MYFXQ}' style="width:100%;height:100%"  />`
    view_FQX.innerHTML = MYFQX;
  })
}

function Signet1() {
  isSeal1.value = true
  // // 生成章
  nextTick(() => {
    const MYFXQ = FXQ.companySeal('***', 0, 0, '', '');
    let view_FQX = document.querySelector("#view_FQX2");
    let MYFQX = `<img src='${MYFXQ}' style="width:100%;height:100%"  />`
    view_FQX.innerHTML = MYFQX;
  })
}

function handleInput() {
  if (inputRegx.test(formData.value.BigMoney) == false) {
    formData.value.BigMoney = ''
    ElMessage.warning('只能输入汉字')
  }
}
async function getSupplierSelection() {
  const data = {
    taskId: route.query.taskId,
    planId: route.query.planId
  }
  let res = await GetHaveInStockPurchaseSupplierEnterprise(data)
  if (res.success) {
    suppierList.value = res.data
  } else {
    ElMessage.error(res.msg)
  }
}
async function handleChangeSup() {
  cancel()
  const data = qs.stringify({
    selId: formData.value.supId,
    taskId: route.query.taskId,
    planId: route.query.planId,
  })
  let res = await GetHaveSignedPurchaseOrderContract(data)
  if (res) {
    contractList.value = res
  } else {
    ElMessage.error(res.msg)
  }
}

async function handleChangeContract(item) {
  //计算商品总额
  const infoList = JSON.parse(item.orderInformation)
  let total = 0
  infoList.forEach(item => {
    total = total + (item.Price * item.Quantity)
  })
  formData.value.money = total
  //通过到货日期加上付款约定的日期
  let handleDate = new Date(item.deliveryDate)
  const matchedItem = paymentList.value.find(a => a.dictId === item.paymentAgreement);
  if (matchedItem) {
    const daysToAdd = parseInt(matchedItem.dictName.replace(/[^0-9]/g, ''));
    handleDate.setDate(handleDate.getDate() + daysToAdd);
  } else {
    handleDate.setDate(handleDate.getDate() + 30);
  }
  formData.value.year = handleDate.getFullYear();
  formData.value.month = String(handleDate.getMonth() + 1).padStart(2, '0');
  formData.value.day = String(handleDate.getDate()).padStart(2, '0');
  formData.value.collectionDate = `${formData.value.year}-${formData.value.month}-${formData.value.day} 00:00:00`
  formData.value.BigMoney = ''
}
//切换供应商清空表单
function cancel() {
  contractList.value = []
  formData.value.month = ''
  formData.value.year = ''
  formData.value.day = ''
  formData.value.collectionDate = ''
  formData.value.money = ''
  formData.value.BigMoney = ''
  formData.value.contractId = ''
  isSeal.value = false
  isSeal1.value = false
}
//关闭弹窗
function cancel1() {
  contractList.value = []
  formData.value.month = ''
  formData.value.year = ''
  formData.value.day = ''
  formData.value.supId = ''
  formData.value.collectionDate = ''
  formData.value.money = ''
  formData.value.BigMoney = ''
  formData.value.contractId = ''
  isSeal.value = false
  isSeal1.value = false
  addVisible.value = false
}
async function save() {
  if (!isSeal.value) {
    ElMessage.warning("承诺人未盖章")
    return
  }
  if (!isSeal1.value) {
    ElMessage.warning("法人代表未盖章")
    return
  }
  if (!formData.value.supId) {
    ElMessage.warning("请先选择公司")
    return
  }
  if (!formData.value.contractId) {
    ElMessage.warning("请先选择合同")
    return
  }
  if (!formData.value.BigMoney) {
    ElMessage.warning("请输入大写金额")
    return
  }
  let data = {
    seiId: formData.value.supId,
    purchaseSaleContractId: formData.value.contractId,
    contractAmount: formData.value.money,
    contractAmountInwords: formData.value.BigMoney,
    taskId: route.query.taskId,
    planId: route.query.planId,
    collectionDate: formData.value.collectionDate,
    PurchaseName: contractList.value.find(item => item.purchaseSaleContractId == formData.value.contractId).purchaseName
  }
  let res = await AccountsReceivableCertificateCreate(data)
  if (res.success) {
    ElMessage.success('发送应收账款凭证成功！')
    cancel1()
    getList()
  } else {
    ElMessage.error(res.msg)
  }
}
onMounted(async () => {
  let data = qs.stringify({
    dictCode: 'DuePaymentDate'
  })
  const res = await GetDictionaryByDictCode(data)
  if (res.success) {
    paymentList.value = res.data
  } else {
    ElMessage.error(res.msg)
  }
  getSupplierSelection()
  getList()
})

async function getList() {
  const data = {
    planId: route.query.planId,
    taskId: route.query.taskId,
    pageIndex: pagination.currentPage,
    pageCount: pagination.pageSize,
  }
  let res = await AccountsReceivableCertificateGetAllByPagedAndSort(data)
  if (res.status == 200) {
    res.data.items.forEach(item => {
      item.collectionDate = item.collectionDate.substring(0, 10)
    })
    dataList.value = res.data.items
    pagination.total = res?.data.totalCount;
  } else {
    ElMessage.error(res.msg);
  }
}

</script>
<style scoped lang="scss">
@import url(@/style/CreditComm.scss);

.container {
  display: flex;
  justify-content: center;
}

.content {
  text-align: center;
}

.company {
  font-size: 24px;
  font-weight: bold;
}

.signature {
  display: flex;
  justify-content: space-between;
}

.signatory p {
  margin: 0;
}

.DispatchForm_date {
  display: flex;
  border-top: none;
  margin-left: 15px;

  margin-top: 50px;

  ul {
    width: 50%;
    text-align: left;
    position: relative;

    li {
      line-height: 32px;
    }
  }
}

.mySignet {
  position: absolute;
  width: 130px;
  height: 130px;
  left: 13%;
  top: -100%;
}

.foot-buttom {
  display: flex;
  justify-content: center;
  margin-top: 100px;
}
</style>
